<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>店铺雷达</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            background-color: #f0f0f0; /* Fallback background */
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: sans-serif;
            -webkit-tap-highlight-color: transparent; /* 隐藏移动设备点击高亮 */
        }

        .radar-container {
            position: relative;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            background: url('./img/index.png') no-repeat center center;
            background-size: cover;
        }

        .radar-container video {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 100%;
            height: 100%;
            min-width: 100%;
            min-height: 100%;
            margin: -0px;
            background: url('./img/index.png') no-repeat center center;
            background-size: cover;
            z-index: 0;
            object-fit: cover;
        }


        .radar-container::before {
            width: 66%;
            height: 66%;
        }

        .radar-container::after {
            width: 33%;
            height: 33%;
        }

        .center-heart {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 40px; /* Adjust size as needed */
            height: 40px;
            background-color: rgba(255, 105, 180, 0.7); /* Pink heart color */
            border-radius: 50% 50% 0 0 / 50% 50% 0 0; /* Simple heart shape */
            clip-path: polygon(50% 100%, 0 30%, 0 0, 100% 0, 100% 30%); /* More accurate heart shape */
            opacity: 0.8;
        }


        .shop-item {
            position: absolute;
            display: flex;

            align-items: center;
            background-color: rgba(255, 255, 255, 0.85);
            border-radius: 200px;
            padding: 5px;
            padding-right: 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            transition: transform 0.5s ease-out, opacity 0.5s ease-out; /* For gradual loading */
            opacity: 0; /* Start hidden for gradual loading */
            transform: scale(0.3) translate(-50%, -50%); /* Start small and centered for animation */
            cursor: pointer;
            white-space: nowrap; /* Prevent text wrapping */
            transform-origin: center center;
        }

        .shop-item.visible {
            opacity: 1;
            transform: scale(0.7) translate(-50%, -50%); /* Animate to full size and correct position */
        }

        .shop-image {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid white;
            margin-right: 8px;
        }

        .shop-info {
            font-size: 10px; /* Smaller font size */
            line-height: 1.3;
            color: #333;
            overflow: hidden;
        }

        .shop-info div {
            margin-bottom: 1px;
        }

        .shop-name {
            font-weight: bold;
            font-size: 11px; /* Slightly larger name */
        }
    </style>

    <style>
        /* 移动端自动滚动样式 */
        .shop-name {
            font-weight: bold;
            font-size: 11px;
            max-width: 60px;
            white-space: nowrap;
            display: block; /* 确保元素是块级的 */
        }

        .shop-name.scrollable {
            animation: marquee 8s linear infinite;
            padding-right: 10px;
        }

        @keyframes marquee {
        0% { transform: translateX(0); }
        10% { transform: translateX(0); }
        90% { transform: translateX(calc(-100%)); } /* 修改为更简单的计算 */
        100% { transform: translateX(0); }
        }



        .shop-item {
            position: absolute;
            display: flex;
            align-items: center;
            background-color: rgba(255, 255, 255, 0.85);
            border-radius: 200px;
            padding: 5px;
            padding-right: 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            transition: transform 0.5s ease-out, opacity 0.5s ease-out; /* 保留原有过渡效果 */
            opacity: 0;
            transform: scale(0.3) translate(-50%, -50%);
            cursor: pointer;
            white-space: nowrap;
            transform-origin: center center;
            user-select: none; /* 防止文本选择 */
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            touch-action: manipulation; /* 优化触摸行为 */
        }

        .shop-item.visible {
            opacity: 1;
            transform: scale(0.7) translate(-50%, -50%);
        }

        /* 点击动画效果 */
        @keyframes pulse {
            0% { transform: scale(0.7) translate(-50%, -50%); box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); }
            25% { transform: scale(0.75) translate(-50%, -50%); box-shadow: 0 0 15px rgba(255, 105, 180, 0.7); }
            50% { transform: scale(0.7) translate(-50%, -50%); box-shadow: 0 0 10px rgba(255, 105, 180, 0.5); }
            75% { transform: scale(0.73) translate(-50%, -50%); box-shadow: 0 0 12px rgba(255, 105, 180, 0.6); }
            100% { transform: scale(0.7) translate(-50%, -50%); box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); }
        }

        .shop-item.clicking {
            animation: pulse 1s ease-in-out;
        }

    </style>
</head>
<body>
<div class="radar-container" id="radarContainer">
    <video autoplay muted loop id="bgVideo" preload="auto" playsinline>
        <source src="./video/index.mp4" type="video/mp4">
    </video>
    <!-- Shop items will be added here dynamically -->
</div>

<script>
    const radarContainer = document.getElementById('radarContainer');
    let currentShopData = []; // Store current data to detect changes
    let maxDistance = 10000; // Default max distance, will be updated
    const MAX_ITEMS = 20; // Maximum items to display
    const BASE_URL = 'http://app.playtruly.cn:1115'; // Adjust if your base URL is different

    // --- 修改开始：添加 displayedMaxDistance 参数 ---
    function calculatePosition(distance, index, totalItems, displayedMaxDistance) {
    // --- 修改结束 ---
        const radarRadius = radarContainer.offsetWidth / 2;

        // --- 修改开始：使用 displayedMaxDistance 进行归一化 ---
        // 确保 displayedMaxDistance 大于 0
        const effectiveMaxDistance = Math.max(1, displayedMaxDistance);
        // 归一化距离，范围限制在 0.05 到 1 之间
        const normalizedDistance = Math.max(0.05, Math.min(1, distance / effectiveMaxDistance));
        // --- 修改结束 ---

        // Distribute items somewhat evenly around the circle
        const angle = (index / totalItems) * 2 * Math.PI + (Math.random() - 0.5) * 0.5; // Add some randomness

        // Calculate radius on radar (closer items have smaller radius)
        // 使用归一化距离乘以可用半径
        const radius = normalizedDistance * (radarRadius * 0.7); // 稍微增大可用半径范围到85%

        // Convert polar to Cartesian coordinates (relative to center)
        const x = radius * Math.cos(angle);
        const y = radius * Math.sin(angle);

        // Convert to top/left percentages relative to container
        const left = 50 + (x / radarRadius) * 50;
        const top = 50 + (y / radarRadius) * 50;

        return { top: `${top}%`, left: `${left}%` };
    }

    // Function to handle image loading errors
    function imageError(event) {
        const defaultImage = './img/imgdef.webp'; // Path to your default image
        if (event.target.src.includes(defaultImage)) {
            // Already tried default, prevent loop
            event.target.removeEventListener('error', imageError);
            return;
        }
        event.target.src = defaultImage;
    }

    // Function to update the radar display
    function updateRadar(shopData) {
        // Sort by distance (ascending)
        // shopData.sort((a, b) => a.distance - b.distance);
        // 反转数组，让新数据（底部）移到前面
        const reversedData = [...shopData].reverse();
        // 从反转后的数组顶部开始限制到 MAX_ITEMS
        const itemsToDisplay = reversedData.slice(0, MAX_ITEMS);


        // --- 修改开始 ---
        // 计算当前显示项目中的最大距离，用于动态缩放
        // 添加一个最小距离，防止所有距离都为0或非常小的情况
        const displayedMaxDistance = itemsToDisplay.length > 0
            ? Math.max(...itemsToDisplay.map(item => item.distance), 1) // 确保至少为1，避免除零
            : 1; // 如果没有项目，默认为1
        // --- 修改结束 ---

        // 清除旧项目
        // 使用 Set 来跟踪已添加的 commentId，避免重复添加DOM元素（虽然理论上不应该发生）
        const existingItems = radarContainer.querySelectorAll('.shop-item');
        const existingIds = new Set(Array.from(existingItems).map(el => el.dataset.commentId));
        const itemsToRemove = [];
        const itemsToUpdate = new Map(); // Store existing elements to potentially update position

        existingItems.forEach(item => {
            const commentId = item.dataset.commentId;
            const correspondingNewItem = itemsToDisplay.find(shop => String(shop.commentId) === commentId);
            if (!correspondingNewItem) {
                itemsToRemove.push(item); // Mark for removal if not in new data
            } else {
                itemsToUpdate.set(commentId, item); // Keep track of existing item
            }
        });

        // 移除不再显示的项目
        itemsToRemove.forEach(item => item.remove());


        itemsToDisplay.forEach((shop, index) => {
            const commentIdStr = String(shop.shopId);
            let shopElement = itemsToUpdate.get(commentIdStr); // Try to find existing element

            // 计算新位置 (使用动态最大距离)
            const position = calculatePosition(shop.distance, index, itemsToDisplay.length, displayedMaxDistance); // 传递 displayedMaxDistance

            if (shopElement) {
                // 更新现有元素的位置 (如果需要动画，可以在这里处理)
                shopElement.style.left = position.left;
                shopElement.style.top = position.top;
                // 可选：更新内容，如果内容可能变化
                // updateShopElementContent(shopElement, shop);
            } else {
                // 创建新的店铺元素
                shopElement = document.createElement('div');
                shopElement.classList.add('shop-item');
                shopElement.dataset.commentId = commentIdStr; // Store ID for tracking

                shopElement.style.left = position.left;
                shopElement.style.top = position.top;

                // 提取数据
                const shopName = shop.shopName || '未知店铺';
                let shopImage = './img/imgdef.webp';
                if (shop.latestComment.commentImages.length > 0) {
                    shopImage = shop.latestComment.commentImages[0].startsWith('/') ? BASE_URL + shop.latestComment.commentImages[0] : shop.latestComment.commentImages[0];
                }
                const checkIns = shop.shopCheckInCount !== undefined ? shop.shopCheckInCount : '?';
                const comments = shop.shopCommentCount !== undefined ? shop.shopCommentCount : '?';

                // 填充内容
                shopElement.innerHTML = `
                    <img src="${shopImage}" class="shop-image" alt="${shopName}" onerror="imageError(event)">
                    <div class="shop-info">
                        <div class="shop-name">${shopName}</div>
                        <div>打卡: ${checkIns}</div>
                        <div>评论: ${comments}</div>
                    </div>
                `;
// 修改：使用requestAnimationFrame确保DOM已更新
requestAnimationFrame(() => {
    const shopNameElement = shopElement.querySelector('.shop-name');

    // 创建一个临时span来测量实际宽度
    const testSpan = document.createElement('span');
    testSpan.style.visibility = 'hidden';
    testSpan.style.position = 'absolute';
    testSpan.style.whiteSpace = 'nowrap';
    testSpan.style.fontSize = '11px';
    testSpan.style.fontWeight = 'bold';
    testSpan.innerText = shopName;
    document.body.appendChild(testSpan);

    // 检测是否超过6个字符并且宽度超过容器
    if (shopName.length > 6 && testSpan.offsetWidth > 80) {
        shopNameElement.classList.add('scrollable');
        // 添加额外的内容用于无缝滚动（仅添加一次）
        shopNameElement.innerHTML = `${shopName} &nbsp;&nbsp;&nbsp;`;
    }

    // 清理测试元素
    document.body.removeChild(testSpan);
});
                // 添加点击监听器
                shopElement.onclick = () => {
                    console.log('Clicked shop:', shop);

                    // 添加点击动画
                    shopElement.classList.add('clicking');

                    // 2秒后移除动画类
                    setTimeout(() => {
                        shopElement.classList.remove('clicking');
                    }, 2000);

                    // 原有的功能保持不变
                    if (shop) {
                        Android.openShopDetail(JSON.stringify(shop));
                    } else {
                        alert(`打开店铺详情: ${shopName} (ID: ${shop.commentId})`);
                    }
                };

                // 添加到容器 (初始隐藏)
                radarContainer.appendChild(shopElement);

                // 渐进显示
                // 使用 requestAnimationFrame 确保元素已添加到DOM并应用初始样式
                requestAnimationFrame(() => {
                    setTimeout(() => {
                        shopElement.classList.add('visible');
                    }, index * 100); // 稍微加快动画间隔
                });
            }
        });
    }

    // Function to fetch data from Android
    function fetchData() {
        try {
            if (Android && typeof Android.onHomePageAnimShow === 'function') {
                Android.onHomePageAnimShow();
                // 不再在这里直接处理数据，而是由Android调用window.radar_scan
            } else {
                console.warn("Android接口不可用，使用测试数据");
                // 测试用 - 直接调用radar_scan函数
                window.radar_scan(JSON.stringify({"data_shop": []}));
            }
        } catch (error) {
            console.error("调用Android接口出错:", error);
        }
    }

    // 优化window.radar_scan函数，增加数据格式的鲁棒性
    window.radar_scan = function(dataString) {
        console.warn("jinlaile")
        try {
            if (!dataString) {
                console.warn("接收到空数据");
                return;
            }

            let shopData = [];

            try {
                // 解析JSON字符串

                // 先确保是字符串
if (typeof dataString !== 'string') {
    dataString = JSON.stringify(dataString);
    console.warn("cuole")

}

            // 清理可能导致JSON解析错误的字符
            // 删除所有未转义的换行符
            dataString = dataString.replace(/\n/g, '');
            // 也可以选择替换为空格：dataString = dataString.replace(/\n/g, ' ');
            
            // 清理其他可能的问题字符
            dataString = dataString.replace(/\r/g, ''); // 删除回车符
            dataString = dataString.replace(/\t/g, ''); // 删除制表符



                const parsedData = JSON.parse(dataString);
                console.warn("ccccccccccccccc")
                // 判断数据类型并提取商店数据
                if (Array.isArray(parsedData)) {
                    // 直接传入了店铺数组
                    shopData = parsedData;
                    console.log("接收到店铺数组数据");
                } else if (parsedData && typeof parsedData === 'object') {
                    // 传入了包含data_shop的对象
                    if (Array.isArray(parsedData.data_shop)) {
                        shopData = parsedData.data_shop;
                        console.log("接收到data_shop对象数据");
                    } else {
                        // 尝试在对象中寻找数组类型的属性
                        const arrayProps = Object.keys(parsedData).filter(key =>
                            Array.isArray(parsedData[key]) &&
                            parsedData[key].length > 0 &&
                            parsedData[key][0] &&
                            typeof parsedData[key][0] === 'object' &&
                            (parsedData[key][0].shopId !== undefined ||
                             parsedData[key][0].latestComment !== undefined)
                        );

                        if (arrayProps.length > 0) {
                            // 使用找到的第一个符合条件的数组
                            shopData = parsedData[arrayProps[0]];
                            console.log(`使用找到的数组属性: ${arrayProps[0]}`);
                        } else {
                            // 如果是单个店铺对象
                            if (parsedData.shopId !== undefined || parsedData.latestComment !== undefined) {
                                shopData = [parsedData];
                                console.log("接收到单个店铺对象");
                            } else {
                                console.warn("无法识别的数据格式");
                                console.log("数据结构:", JSON.stringify(Object.keys(parsedData)));
                            }
                        }
                    }
                }
            } catch (parseError) {
                console.error("JSON解析错误:", parseError);
                return;
            }

            // 验证商店数据的有效性
            if (!Array.isArray(shopData)) {
                console.warn("提取的商店数据不是数组");
                return;
            }

            // 过滤掉无效的店铺数据
            shopData = shopData.filter(shop =>
                shop && typeof shop === 'object' &&
                (shop.shopId !== undefined || shop.latestComment !== undefined)
            );

            // 检查数据是否变化
            if (JSON.stringify(shopData) !== JSON.stringify(currentShopData)) {
                console.log(`数据已更新，刷新雷达... 项目数: ${shopData.length}`);
                currentShopData = shopData;
                updateRadar(currentShopData);
            } else {
                console.log('数据未变化');
            }
        } catch (error) {
            console.error("处理数据出错:", error);
        }
    };

    // Initial fetch and start interval timer
    //fetchData();
    //setInterval(fetchData, 1000); // Fetch every 1 second

    // Adjust radar size on window resize
    window.addEventListener('resize', () => {
         // Re-calculating positions might be needed if size changes significantly
         // For simplicity, we might just rely on vmin units, but a full re-render could be better
         if(currentShopData.length > 0) {
            // Simple re-render on resize
            updateRadar(currentShopData);
         }
    });

</script>
</body>
</html>